package com.cas.utils;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

public class IdGenerator {

    private static final SecureRandom random = new SecureRandom();

    /**
     * 生成一个带前缀的时间戳字符串
     *
     * @param prefix 前缀字符串，可以为null或空字符串
     * @param length 生成的时间戳字符串的总长度（包括前缀）
     * @return 带前缀的时间戳字符串
     * @throws IllegalArgumentException 如果长度小于前缀长度
     */
    public static String generateTimestampWithPrefix(String prefix, int length) {
        if (prefix == null) {
            prefix = "";
        }

        // 获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());

        // 计算需要的时间戳长度
        int timestampLength = length - prefix.length();

        if (timestampLength <= 0) {
            throw new IllegalArgumentException("长度必须大于前缀长度");
        }

        // 截取或填充时间戳以达到所需的长度
        if (timestamp.length() > timestampLength) {
            timestamp = timestamp.substring(0, timestampLength);
        } else {
            timestamp = String.format("%" + timestampLength + "s", timestamp).replace(' ', '0');
        }

        return prefix + timestamp;
    }

    public static String generateRandomNumber(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0到9之间的随机数
            sb.append(digit);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // 示例调用
        System.out.println(generateTimestampWithPrefix("PRE_", 20)); // 输出: PRE_20231005123456789
        System.out.println(generateTimestampWithPrefix(null, 15));   // 输出: 20231005123456789
        System.out.println(generateTimestampWithPrefix("P", 10));     // 输出: P2023100512
    }
}
